﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FileProcessor
{
	public static class SSParser
	{
		public static void Exec(string cmd)
		{
			string tmd = "";
			string[] data = cmd.Split(';');
			if (data.Length==0)
			{
				 tmd= cmd;
			}
			else
			{
				tmd = data[0];
			}
			switch(tmd)
			{
				case "create":
					Processor.CreateSet(data[1]);
					break;
				case "view":
					Processor.ViewSet(int.Parse(data[1]));
					break;
				case "count":
					Processor.SetCount();
					break;
				case "sf":
					Processor.SetFolder(int.Parse(data[1]), data[2]);
					break;
				case "map":
					Processor.Map(int.Parse(data[1]), int.Parse(data[3]), data[2]);
					break;
				case "size":
					Processor.SizeOfSet(int.Parse(data[1]));
					break;
				case "quit":
					Environment.Exit(0);
					break;
				case "help":
					Help();
					break;
			}
		}
		public static void Help()
		{
			Console.WriteLine("create; to create a Set");
			Console.WriteLine("view; to view the Set with a id");
			Console.WriteLine("count; return the num of sets");
			Console.WriteLine("sf; set the Set folder");
			Console.WriteLine("map; map the data from a Set to another Set");
			Console.WriteLine("size; return the size of a set");
			Console.WriteLine("quit; to quit the app");
			Console.WriteLine("_______________________________________");
			Console.WriteLine("Map Function:");
			Console.WriteLine("_______________________________________");
			Processor.MapFunctionHelp();

		}
		public static SubSet SetCreaterExec(string cmd)
		{
			if(cmd.IndexOf("link")>=0)
			{
				SubSet currentSet;
				string[] sscmd;
				cmd = " " + cmd;
				cmd += " ";
				sscmd = Regex.Split(cmd, "link");
				for (int i=0;i<sscmd.Length;i++)
				{
					sscmd[i] = sscmd[i].Substring(1, sscmd[i].Length - 2);
				}
				currentSet = CreateSetSubParser(sscmd[0]);
				for (int i=1;i<sscmd.Length;i++)
				{
					currentSet = SubSetFactory.Link(currentSet, CreateSetSubParser(sscmd[i]));
				}
				return currentSet;
			}
			else
			{
				return CreateSetSubParser(cmd);
			}
		}

		private static SubSet CreateSetSubParser(string cmd)
		{
			SubSet result = new SubSet();
			if (cmd[0]=='f'&&cmd[1]=='r' && cmd[2] == 'o' && cmd[3] == 'm' && cmd[4] == ' ')
			{
				int endto= cmd.IndexOf(" to");
				string from = cmd.Substring(5, endto - 5);
				int endby = cmd.IndexOf(" by");
				string to = cmd.Substring(endto + 4, endby - endto - 4);
				string followby = cmd.Substring(endby + 4);
				string inc = followby.Split(' ')[0];
				string incv = followby.Split(' ')[1];
				result = SubSetFactory.CreatSubSetByOrder(from, to, inc, incv);
			}
			else
			{
				result.AddData(cmd);
			}
			return result;
		}

	}
}
